package com.ruoyi.api;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/wx")
@Anonymous
@CrossOrigin("*")
public class WxLoginController {

    @Value("${wx.mini.appid}")
    private String appid;

    @Value("${wx.mini.secret}")
    private String secret;

    // 微信官方接口：用code换openid
    private static final String WX_CODE2SESSION_URL =
            "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    @Resource
    private RestTemplate restTemplate;

    /**
     * 个人小程序获取openid（通用接口，个人/企业账号均可用）
     */
    @PostMapping("/getOpenid")
    public Map<String, Object> getOpenid(@RequestBody Map<String, String> codeMap) {
        Map<String, Object> result = new HashMap<>();
        String code = codeMap.get("code");

        if (code == null || code.isEmpty()) {
            result.put("success", false);
            result.put("msg", "请先获取微信登录凭证");
            return result;
        }

        try {
            // 调用微信接口换取openid
            String url = String.format(WX_CODE2SESSION_URL, appid, secret, code);
            HttpHeaders headers = new HttpHeaders();
            HttpEntity<String> entity = new HttpEntity<>(headers);
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            String responseBody = response.getBody();

            if (responseBody == null) {
                result.put("success", false);
                result.put("msg", "获取openid失败，微信接口无返回");
                return result;
            }

            // 解析微信返回结果
            JSONObject jsonObject = JSONObject.parseObject(responseBody);
            if (jsonObject.containsKey("errcode") && jsonObject.getInteger("errcode") != 0) {
                result.put("success", false);
                result.put("msg", "微信授权失败：" + jsonObject.getString("errmsg"));
                return result;
            }

            String openid = jsonObject.getString("openid");
            if (openid == null || openid.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未获取到openid，请重试");
                return result;
            }

            // 返回openid（前端需保存，用于注册/登录）
            result.put("success", true);
            result.put("data", new HashMap<String, String>() {{
                put("openid", openid);
            }});

        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "获取openid异常：" + e.getMessage());
            e.printStackTrace();
        }

        return result;
    }
}
